//
//  CLWorkAreaDetailViewController.m
//  ZhuKuang
//
//  Created by jjkj on 17/7/11.
//  Copyright © 2017年 jjkj. All rights reserved.
//
#define kWorkDetailCellHeight 44
#define kHeaderViewHeight 45
#define kFooterViewHeight 45
#define kStatusBarAndNavigationBarHeight 64
#define kSwitchViewHeight 50
#define kWorkAreaDetailTableViewHeight (kScreenHeight - kHeaderViewHeight - kFooterViewHeight - kStatusBarAndNavigationBarHeight - kSwitchViewHeight)


#import "CLWorkAreaDetailViewController.h"
#import "CLWorkAreaDetailCell.h"
#import "FCSwitchView.h"
#import "CLWorkAreaDetailHeaderView.h"
#import "CLWorkAreaDetailFooterView.h"
#import "CarShopModel.h"
#import "CLSpeedAndOilLossCurveController.h"
#import "ChooseDateView.h"
#import "CarShopListModel.h"

@interface CLWorkAreaDetailViewController () <UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView *workDetailTableView;//工作明细列表

@property (nonatomic,strong) NSMutableArray *carShopListArray;//工作明细数据源

@property (nonatomic,strong) CLWorkAreaDetailHeaderView *headerView;//区头视图

@property (nonatomic,strong) CLWorkAreaDetailFooterView *footerView;//区头视图
@property (nonatomic,strong) NSMutableDictionary *carShopParamsDic;//请求参数

@property (nonatomic,copy) NSString *mileTotal;

@property (nonatomic,strong) NSString *oilTotal;//

@property (nonatomic,strong) ChooseDateView *myDateView;

@property (nonatomic,copy) NSString *startTime;//开始时间

@property (nonatomic,copy) NSString *endTime;//结束时间



@end

@implementation CLWorkAreaDetailViewController

-(UITableView *)workDetailTableView {
    
    if (!_workDetailTableView) {
        
        _workDetailTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.headerView.frame), kScreenWidth, kWorkAreaDetailTableViewHeight) style: UITableViewStylePlain];
        
        self.workDetailTableView.delegate = self;
        self.workDetailTableView.dataSource = self;
       
        self.workDetailTableView.rowHeight = kWorkDetailCellHeight;
        self.workDetailTableView.bounces = NO;
        self.workDetailTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        [self.workDetailTableView registerNib:[UINib nibWithNibName:@"CLWorkAreaDetailCell" bundle:nil] forCellReuseIdentifier:@"workDetailCell"];
    }
    
    return _workDetailTableView;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.checkType = checkByCarType;
    
    [self titleView];
    
    [self setUpSwitchViewAppeareace];
    [self setUpWorkAreaDetailHeaderView];
    [self setUpWorkAreaDetailFooterView];
    
    [self.view addSubview:self.workDetailTableView];
    
    [self setUpTimeInfo];
    
   
    self.carShopParamsDic = [NSMutableDictionary dictionaryWithDictionary:@{
                                                                            
                     @"starttime":self.startTime,
                     @"endtime":self.endTime,
                     @"type":@"1",
                     @"carShopId":self.carShopId,
                     }];

    [self getCarShopInfoListWith:self.carShopParamsDic];
    // Do any additional setup after loading the view.
}


- (void)setUpTimeInfo {

    NSString *todayDate = [CommClass getTodayDateStr];
    
    if (nil == self.startTime) {
        self.startTime = todayDate;
    }
    
    if (nil == self.endTime) {
        self.endTime = todayDate;
    }

}

//设置选项卡
-(void)setUpSwitchViewAppeareace {
    
    [self.switchView setUpSwitchViewTitleWith:@[@"按卡车查看",@"按司机查看"]];
    
    __weak typeof(self) weakSelf = self;
    
    self.switchView.switchActionBlock = ^(NSInteger tag){
        
        NSLog(@"按照司机或卡车查询");
        
        if (0 == tag - 100) {
            weakSelf.checkType = checkByCarType;
            weakSelf.headerView.driverOrCarName.text = @"卡车";
        }else {
            weakSelf.checkType = checkByDriverType;
             weakSelf.headerView.driverOrCarName.text = @"司机";
        }
        
        [weakSelf.workDetailTableView reloadData];
    };
}

- (void)setUpWorkAreaDetailHeaderView {
    
    self.headerView = [[NSBundle mainBundle] loadNibNamed:@"CLWorkAreaDetailHeaderView" owner:self options:nil].firstObject;
    self.headerView.frame = CGRectMake(0, CGRectGetMaxY(self.switchView.frame), kScreenWidth, 45);
    __weak typeof(self) weakSelf = self;
    
    self.headerView.sortCarBlock = ^(UIButton *sender){
        
        BOOL isAscend = YES;
        if (YES == sender.selected) {//按钮选中降序排列 未选中升序排列
            isAscend = NO;
        }
        [weakSelf sortCarShopListWithTagId:sender.tag andSortType:isAscend];
    };
    
    [self.view addSubview:self.headerView];

}

- (void)setUpWorkAreaDetailFooterView {
    
    self.footerView  = [[NSBundle mainBundle] loadNibNamed:@"CLWorkAreaDetailFooterView" owner:self options:nil].firstObject;
    self.footerView.frame = CGRectMake(0, kScreenHeight - kFooterViewHeight, kScreenWidth, kScreenHeight);
    [self.view addSubview:self.footerView];
    
}
#pragma mark - 排序

- (void)sortCarShopListWithTagId:(NSInteger)tagId  andSortType:(BOOL)isAscend {
    
  
   NSArray *resultArray = [self.carShopListArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
       
       CarShopModel *firstCarModel = obj1;
       CarShopModel *secondCarModel = obj2;
       
       BOOL isGreater = NO;
       if (isAscend) {//升序排列
           
           if (400 == tagId) {//按照油耗排序
               
               isGreater = [firstCarModel.iolloss floatValue] > [secondCarModel.iolloss floatValue];
               
           }else {//按照里程排序
               
               isGreater = [firstCarModel.mile floatValue] > [secondCarModel.mile floatValue];
           }

       }else {//降序排列
       
           if (400 == tagId) {//按照油耗排序
               isGreater = [firstCarModel.iolloss floatValue] < [secondCarModel.iolloss floatValue];
    
           }else {//按照里程排序
               
               isGreater = [firstCarModel.mile floatValue] < [secondCarModel.mile floatValue];
           }

       }
       
       if (isGreater) {
           return NSOrderedDescending;
       }
       return NSOrderedAscending;
       
    }];
    
    self.carShopListArray = [NSMutableArray arrayWithArray:resultArray];
    
    [self.workDetailTableView reloadData];
}
//设置总油耗和里程
- (void)setUpTotalData {
    
    self.footerView.totalMile.text = [NSString stringWithFormat:@"%.2f",[self.mileTotal floatValue]];
    self.footerView.totalOilLoss.text = [NSString stringWithFormat:@"%.2f",[self.oilTotal floatValue]];
    
}


#pragma mark - UITableView delegate and datasource

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.carShopListArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CarShopModel *model = self.carShopListArray[indexPath.row];
    CLWorkAreaDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"workDetailCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setObjectWith:model checkType:self.checkType];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    //CLSpeedAndOilLossCurveController *curveVC = [[CLSpeedAndOilLossCurveController alloc] init];
    //[self.navigationController pushViewController:curveVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 重写导航条左右按钮
- (void)titleView{
    
    UILabel *label = [[UILabel alloc]init];
    label.text = [NSString stringWithFormat:@"%@明细查看",self.seleetdCarShopModel.name];
    label.bounds = CGRectMake(0, 0, 100, 44);
    label.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = label;
    
    // 下个视图的返回按钮
    
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:[self leftButtonItem]];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:[self rightButtonItem]];
}
- (UIView *)leftButtonItem {
    
    UIButton *left = [UIButton buttonWithType:UIButtonTypeCustom];
    left.frame = CGRectMake(0, 0, 30, 30);
    [left setBackgroundImage:[UIImage imageNamed:@"leftArrow"] forState:UIControlStateNormal];
    [left addTarget:self action:@selector(leftButtonItemAction) forControlEvents:UIControlEventTouchUpInside];
    return left;
}


- (void)leftButtonItemAction {
    [self.navigationController popViewControllerAnimated:YES];

}
#pragma mark - rightButtonItem
- (UIView *)rightButtonItem {
    
    UIButton *right = [UIButton buttonWithType:UIButtonTypeCustom];
    right.frame = CGRectMake(0, 0, 30, 30);
    [right setBackgroundImage:[UIImage imageNamed:@"book"] forState:UIControlStateNormal];
    [right addTarget:self action:@selector(rightButtonItemAction) forControlEvents:UIControlEventTouchUpInside];
    return right;
}

#pragma mark - rightButtonItemAction
- (void)rightButtonItemAction {
    [self DateSelectedButtonClick];
    NSLog(@"弹出时间选择框");
}

#pragma mark - 日期选择
- (void)DateSelectedButtonClick{
    
    __weak typeof(self) weakself = self;
    if (!_myDateView) {
        
        _myDateView = [[ChooseDateView alloc]initWithFrame:self.view.bounds];
        _myDateView.backgroundColor = [UIColor whiteColor];
        [_myDateView setHidden:NO];
        
        _myDateView.selectDateCompletionHandle = ^(NSString *beginTime, NSString *endTime){
            
            NSLog(@"%@ - %@",beginTime, endTime);
            
            weakself.startTime = beginTime;
            weakself.endTime = endTime;
            
        //请求数据
            [weakself.carShopParamsDic setObject:weakself.startTime forKey:@"starttime"];
            [weakself.carShopParamsDic setObject:weakself.endTime forKey:@"endtime"];
            [weakself getCarShopInfoListWith:weakself.carShopParamsDic];
        };
        
        [self.view addSubview:_myDateView];
    }
    else{
        
        [_myDateView setHidden:NO];
    }
}

#pragma mark - 网络请求

- (void)getCarShopInfoListWith:(NSMutableDictionary *)dic {
    __weak typeof(self) weakSelf = self;
    
    [CarShopModel getCarShopInfoList:dic success:^(NSDictionary *response) {
        NSLog(@"getCarShopInfo_____%@response",response);
        
        weakSelf.carShopListArray = [NSMutableArray array];
        
        NSArray *shopListArray = response[@"carShopList"];
        weakSelf.oilTotal = response[@"iollosstotal"];
        weakSelf.mileTotal = response[@"miletotal"];
       [weakSelf setUpTotalData];
        
        for (NSDictionary *dic in shopListArray) {
            CarShopModel *carShopModel = [CarShopModel mj_objectWithKeyValues:dic];
            [weakSelf.carShopListArray addObject:carShopModel];
        }
        
        [weakSelf.workDetailTableView reloadData];
    }];
}


@end
